package com.central.common.handler;

import cn.hutool.json.JSONUtil;
import com.central.common.entity.TaskParams;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @author Tindy
 * @date 2021/6/23
 * @describe
 */
@MappedJdbcTypes(JdbcType.VARCHAR)  // 数据库类型
@MappedTypes({TaskParams.class})          // java数据类型
public class TaskParamsToStringHandler extends BaseTypeHandler<TaskParams> {

    @Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int i, TaskParams taskParams, JdbcType jdbcType) throws SQLException {
        preparedStatement.setString(i, JSONUtil.toJsonStr(taskParams));
    }

    @Override
    public TaskParams getNullableResult(ResultSet resultSet, String s) throws SQLException {
        TaskParams taskParams = JSONUtil.toBean(resultSet.getString(s), TaskParams.class);
        return taskParams;
    }

    @Override
    public TaskParams getNullableResult(ResultSet resultSet, int i) throws SQLException {
        TaskParams taskParams = JSONUtil.toBean(resultSet.getString(i), TaskParams.class);
        return taskParams;
    }

    @Override
    public TaskParams getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
        TaskParams taskParams = JSONUtil.toBean(callableStatement.getString(i),TaskParams.class);
        return taskParams;
    }
}

